/**
 * Created by Administrator on 2017/11/15/015.
 */
SCOPE.layim_page_num = 0;
layui.config({
    version: true,
    base: '/static/layui_layim/base/js/'
}).extend({
    rmlib: 'rmlib',
    protobuf: 'protobuf',
    socket: 'socket',
}).use(['mobile', 'jquery'], function(){
    var mobile = layui.mobile
        ,layim = mobile.layim
        ,$ = layui.$
        ,layer = mobile.layer;

    layim.config({
        brief: true, //简约模式，不显示主面板

        //上传图片接口
        uploadImage: {
            url: SCOPE.upload_image_url //（返回的数据格式见下文）
            ,type: '' //默认post
        }

        ,init: {
            //我的信息
            mine : SCOPE.mine_info

        }

        ,members: {
            url: SCOPE.members_url
            ,data: {}
        }

        , isAudio: true //开启聊天工具栏音频
        , isVideo: true //开启聊天工具栏视频

        ,tabIndex: 0 //用户设定初始打开的Tab项下标
        ,isNewFriend: false //是否开启“新的朋友”
        ,isgroup: true //是否开启“群聊”
        ,chatTitleColor: '#c00' //顶部Bar颜色
        ,title: '消息中心' //应用名，默认：我的IM
        ,chatLog: layui.cache.dir + 'css/modules/layim/html/chatLog.html'
    });

    layim.chat({
        name: SCOPE.target_info.username //名称
        ,type: SCOPE.target_info.type //聊天类型
        ,avatar: SCOPE.target_info.avatar //头像
        ,id: SCOPE.target_info.id //好友id
    });

    //监听返回
    layim.on('back', function(){
        if (SCOPE.layim_page_num == 0) {
            history.back();
        } else {
            SCOPE.layim_page_num--;
        }
    });

    //监听发送消息
    layim.on('sendMessage', function(data){
        data.mine.rong_content = data.to.rong_content = replace_content(data.mine.content);;

        $.ajax({
            type : 'POST',
            url : SCOPE.sendMsgUrl,
            data : data,
            dataType : 'json',
            success : function (msg) {
                console.log(msg);
            }
        });
    });

    // 监听点击群员
    layim.on('detail', function(data){
        $(".diy_layer").show();
        SCOPE.layim_page_num++;
        $.get(SCOPE.members_url, data, function (msg) {
            var list_tpl = '<ul>';
            layui.each(msg.data.list, function(index, item){
                list_tpl += '<li class="members"><img src="'+item.avatar+'"><p>'+item.username
                    if (item.identity == 1) {
                        list_tpl += '<span>管理员</span>';
                    }
                list_tpl += '</p></li>';
            });
            list_tpl += '</li>';

            layim.panel({
                title: data.name + ' 群组成员' //标题
                ,tpl: list_tpl //模版
                ,data: '' // 数据
            });
            $(".diy_layer").hide();
        }, 'json');
    });

    //监听查看私聊更多记录
    layim.on('chatlog', function(data, ul){
        $(".diy_layer").show();
        $.get(SCOPE.get_msg_url, data, function (msg) {
            var list_tpl = '<div class="layim-chat layim-chat-group"><div class="layim-chat-main aaaaaaaa" style="bottom: 0;"><ul class="chatlog_list">';

            layui.each(msg, function(index, item){
                var content = replace_content(item.content);
                if(item.id == SCOPE.mine_info.id){
                    list_tpl += '<li class=" layim-chat-li layim-chat-mine log"><div class="layim-chat-user"><img src="'+item.avatar+'"><cite><i>'+item.timestamp+'</i>'+item.username+'</cite></div><div class="layim-chat-text">'+content+'</div></li>';
                } else{
                    list_tpl += '<li class="layim-chat-li log"><div class="layim-chat-user"><img src="'+item.avatar+'"><cite>'+item.username+'<i>'+item.timestamp+'</i></cite></div><div class="layim-chat-text">'+content+'</div></li>';
                }
            });
            list_tpl += '</ul></div></div>';

            layim.panel({
                title:  '与 '+ data.name +' 的聊天记录' //标题
                ,tpl: list_tpl //模版
                ,data: '' // 数据
            });

            $('.aaaaaaaa').animate({
                scrollTop: $(".chatlog_list").height()
            }, 0);
            $(".diy_layer").hide();
        }, 'json');
    });

    var callbacks = {
        getInstance : function(instance){

        },
        getCurrentUser : function(userInfo){
            console.log(userInfo.userId);
            userId = userInfo.userId;
        },
        receiveNewMessage : function(message){
            //判断是否有 @ 自己的消息
            var mentionedInfo = message.content.mentionedInfo || {};
            var ids = mentionedInfo.userIdList || [];
            for(var i=0; i < ids.length; i++){
                if( ids[i] == userId){
                    alert("有人 @ 了你！");
                }
            }
            console.log(message);console.log($.parseHTML(message.content.content));

            if(message.objectName == 'RC:ImgMsg') {
                message.content.content = 'img['+message.content.imageUri+']';
            }

            layim.getMessage({
                username: message.content.user.name
                ,avatar: message.content.user.portrait ? message.content.user.portrait : message.content.user.icon
                ,id: message.targetId
                ,type: message.conversationType == 1 ? 'friend' : 'group'
                ,content: message.content.content
            });
        }
    };

    rong_init(params,callbacks);

    //支持的html标签
    var html = function(end){
        return new RegExp('\\n*\\['+ (end||'') +'(pre|div|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
    };

    //表情库
    var faces = function(){
        var alt = ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]", "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]", "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]", "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]", "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]", "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]", "[话筒]", "[蜡烛]", "[蛋糕]"], arr = {};
        layui.each(alt, function(index, item){
            arr[item] = layui.cache.dir + 'images/face/'+ index + '.gif';
        });
        return arr;
    }();

    function replace_content(content) {
        content = (content||'').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
            .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
            .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@

            .replace(/face\[([^\s\[\]]+?)\]/g, function(face){  //转义表情
                var alt = face.replace(/^face/g, '');
                return '<img alt="'+ alt +'" title="'+ alt +'" src="' + faces[alt] + '">';
            })
            .replace(/img\[([^\s]+?)\]/g, function(img){  //转义图片
                return '<img class="layui-layim-photos" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
            })
            .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str){ //转义文件
                var href = (str.match(/file\(([\s\S]+?)\)\[/)||[])[1];
                var text = (str.match(/\)\[([\s\S]*?)\]/)||[])[1];
                if(!href) return str;
                return '<a class="layui-layim-file" href="'+ href +'" download target="_blank"><i class="layui-icon">&#xe61e;</i><cite>'+ (text||href) +'</cite></a>';
            })
            .replace(/audio\[([^\s]+?)\]/g, function(audio){  //转义音频
                return '<div class="layui-unselect layui-layim-audio" layim-event="playAudio" data-src="' + audio.replace(/(^audio\[)|(\]$)/g, '') + '"><i class="layui-icon">&#xe652;</i><p>音频消息</p></div>';
            })
            .replace(/video\[([^\s]+?)\]/g, function(video){  //转义音频
                return '<div class="layui-unselect layui-layim-video" layim-event="playVideo" data-src="' + video.replace(/(^video\[)|(\]$)/g, '') + '"><i class="layui-icon">&#xe652;</i></div>';
            })

            .replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str){ //转义链接
                var href = (str.match(/a\(([\s\S]+?)\)\[/)||[])[1];
                var text = (str.match(/\)\[([\s\S]*?)\]/)||[])[1];
                if(!href) return str;
                return '<a href="'+ href +'" target="_blank">'+ (text||href) +'</a>';
            }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') //转移HTML代码
            .replace(/\n/g, '<br>') //转义换行
        return content;
    }

    // 点击查看大图
    $(document).on('click', '.layui-layim-photos', function () {
        var _src = $(this).attr('src');
        _src = _src.replace(100,500);
        $("body").append("<div class='show-layui-layim-photos'><img src='"+_src+"' /></div>");
        var _width = $('.show-layui-layim-photos').find('img').width();
        if (_width%2 !=0) {
            _width++;
        }
        $('.show-layui-layim-photos').find('img').css('margin-top', -(_width / 2) + 'px');
    });

    $(document).on('click', '.show-layui-layim-photos', function () {
        $(this).remove();
    });
});

